package com.ruoyi.approval.service.impl;

import com.ruoyi.common.enums.ActivityEnum;
import com.ruoyi.common.utils.ExceptionFinalMessage;
import com.ruoyi.approval.activity.*;
import com.ruoyi.approval.mapper.ApprovalMapper;
import com.ruoyi.approval.pojo.ActivityApprovalPojo;
import com.ruoyi.approval.result.ApprovalResult;
import com.ruoyi.master.domain.PmActivity;
import com.ruoyi.master.mapper.PmActivityMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Date 2021/3/28 11:19
 * @Created mobian
 * @Description 活动审批
 */
@Component
public class ActivityApprovalService extends AbstractApprovalService {

	private static final Logger logger = LoggerFactory.getLogger(AbstractApprovalService.class);


	@Autowired
	private ContentActivityFilter contentActivityFilter;
	@Autowired
	private MemPlaTypeTeaActivityFilter memPlaTypeTeaActivityFilter;
	@Autowired
	private PlaTimeActivityFilter plaTimeActivityFilter;

	@Autowired
	private PmActivityMapper pmActivityMapper;


	@Autowired
	private ApprovalMapper approvalMapper;

	@Override
	protected ActivityApprovalPojo buildApprovalPojo(PmActivity activity) throws ParseException {

		ActivityApprovalPojo approvalPojo = new ActivityApprovalPojo();

		//审批要素:
		if (activity != null) {
			try {

				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				//审批对象id
				approvalPojo.setApprovalId("ACT_" + activity.getId().toString());

				//审批类型
				approvalPojo.setType("ACT_");
				approvalPojo.setLeadTeacher(activity.getLeadTeacher());

				//根据审批对象的id查询对应的审批记录
				List<ActivityApprovalPojo> oldRecord = approvalMapper.queryApprovalRecordList(approvalPojo.getApprovalId());
				//审批状态 审批时间
				if (oldRecord != null && oldRecord.size() == 1) {
					approvalPojo.setStatus(oldRecord.get(0).getStatus());
					approvalPojo.setApprovalCreateDate(oldRecord.get(0).getApprovalCreateDate());

				} else if (oldRecord != null && oldRecord.size() == 0) {
					approvalPojo.setStatus(ActivityEnum.ActivityStateEnum.WAIT.getValue());
					approvalPojo.setApprovalCreateDate(df.parse(df.format(new Date())));

				} else {
					throw new RuntimeException(ExceptionFinalMessage.DATA_IS_ERROR + ":oldRecord");
				}


				//更新时间
				approvalPojo.setApprovalUpdateDate(df.parse(df.format(new Date())));

				//具体的审批要素
				approvalPojo.setApprovalDetail(activity.getActivityContent());
				approvalPojo.setApprovalBeginDate(activity.getBegindate());
				approvalPojo.setApprovalEndDate(activity.getEnddate());
				approvalPojo.setApprovalScale(activity.getScale());
				approvalPojo.setApprovalPlace(activity.getPlace());
				approvalPojo.setApprovalType(activity.getType());

				return approvalPojo;
			} catch (Exception e) {
				logger.error(e.getMessage());
			}
		} else {
			throw new RuntimeException(ExceptionFinalMessage.RECV_MSG_IS_NULL + ":activity");
		}

		return null;
	}

	@Transactional
	public List<ApprovalResult> executeApproval(ActivityApprovalPojo newRecord) throws ParseException {

		boolean isApprovalSuccess = true;

		if (newRecord == null) {
			throw new RuntimeException(ExceptionFinalMessage.BUILD_APPROVAL_ERROR + ":newRecord");
		}

		//添加对应的审批流程
		ActivityFilterChain activityFilterChain = new ActivityFilterChain();
		activityFilterChain.addFilter(contentActivityFilter)
				.addFilter(memPlaTypeTeaActivityFilter)
				.addFilter(plaTimeActivityFilter);

		//执行具体审批操作前，删除历史审批记录
		approvalMapper.deleteApprovalLog(newRecord.getApprovalId());

		List<ApprovalResult> results = activityFilterChain.doFilter(newRecord);


		//添加审批结果到record主表
		for (int i = 0; i < results.size(); i++) {
			if ("10".equals(results.get(i).getCode())) {
				isApprovalSuccess = false;
			}
		}
		Long newRecordId = Long.parseLong(newRecord.getApprovalId().split("_")[1]);
		if (isApprovalSuccess) {
			newRecord.setStatus(ActivityEnum.ActivityStateEnum.SUCCED.getValue());
		} else {
			newRecord.setStatus(ActivityEnum.ActivityStateEnum.FAILED.getValue());
		}

		approvalMapper.deleteApprovalRecord(newRecord.getApprovalId());
		approvalMapper.insertApprovalRecord(newRecord);

		//更新活动表status状态
		pmActivityMapper.updateActivityStatusByApprovalResult(newRecord.getStatus(), newRecord.getApprovalUpdateDate(), newRecordId);
		return results;
	}

}
